package com.wosai.teach.activity;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.android.agoo.client.BaseRegistrar;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.wosai.teach.R;
import com.wosai.teach.cst.AppCst;
import com.wosai.teach.cst.C;
import com.wosai.teach.dialog.NewProgressDialog;
import com.wosai.teach.dto.JsonResult;
import com.wosai.teach.entity.AppUseInfo;
import com.wosai.teach.entity.User;
import com.wosai.teach.pojo.LogLogin;
import com.wosai.teach.utils.AppUtil;
import com.wosai.teach.utils.BitmapHelp;
import com.wosai.teach.utils.OtherUtils;

/**
 * @author qiumy@wosaitech.com 2015-3-28 上午11:22:19
 * 
 *         登录界面
 * 
 */
@ContentView(R.layout.activity_login)
public class LoginActivity extends BaseActivity {
	private Context context;
	private String UserName;
	private String Password;
	@ViewInject(R.id.login_button_login)
	private Button button;

	@ViewInject(R.id.login_head_image)
	private ImageView userHead;
	@ViewInject(R.id.login_nick_name)
	private TextView userNick;

	@ViewInject(R.id.login_button_login)
	private Button buttonLog;
	@ViewInject(R.id.login_txt_register)
	private TextView textReg;
	@ViewInject(R.id.login_et_workcode)
	private EditText editText_workCode;
	@ViewInject(R.id.login_et_password)
	private EditText editText_password;

	private NewProgressDialog progressdialog;
	// private static SharedPreferences sp;
	public static SharedPreferences sp;
	private LogLogin logLogin;
	// @ViewInject(R.id.login_login)
	// private TextView login_login;
	// @ViewInject(R.id.login_bt_forget)
	// private TextView login_bt_forget;
	private String url = AppCst.HTTP_URL + "/appLogin";
	private User user;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// MobclickAgent.onEvent(this, "login");
		super.onCreate(savedInstanceState);
		setmPageName("登录界面，实现判断网络连接、登录功能");
		// setContentView(R.layout.activity_login);
		// enableBack(true);
		ViewUtils.inject(this);
		context = this;

		user = db.findFirst(User.class);

		if (user != null) {
			editText_workCode.setText(user.getLoginName());
			editText_password.setText(user.getPassword());
			System.out.println("||Loginname||" + user.getLoginName()
					+ "||password||" + user.getPassword());
			BitmapUtils bitmapUtils = BitmapHelp
					.getBitmapUtils(getApplicationContext());
			bitmapUtils.configDefaultLoadingImage(R.drawable.img_login);
			bitmapUtils.configDefaultLoadFailedImage(R.drawable.img_login);
			bitmapUtils.display(userHead, user.getIcon1());
		}

		initLogin();
	}

	private void initLogin() {
		logLogin = new LogLogin();
		logLogin.init(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		context = this;
	}

	@OnClick(value = { R.id.login_txt_register })
	public void login_txt_registerCilck(View v) {
		System.out.println("忘记密码！");
		toastShow("请联系任课老师对账号密码进行重置！");
	}

	@OnClick(value = { R.id.login_button_login })
	public void login_button_loginClick(View v) {
		System.out.println("==========点击登录按钮==========");
		UserName = editText_workCode.getText().toString();
		Password = editText_password.getText().toString();
		if (TextUtils.isEmpty(UserName.trim())) {
			// Toast.makeText(getApplicationContext(), "请输入登录名",
			// Toast.LENGTH_SHORT)
			// .show();
			toastShow("请输入登录名");
		} else if (TextUtils.isEmpty(Password.trim())) {
			// Toast.makeText(getApplicationContext(), "请输入密码",
			// Toast.LENGTH_SHORT)
			// .show();
			toastShow("请输入密码");
		} else {
			GetLoginInfo(UserName, Password);
		}
	}

	private void GetLoginInfo(final String UserName, final String Password) {

		if (!checkNetWorkStatus(getApplicationContext())) {
			toastShow("网络忘记连接啦！");
			// Toast.makeText(LoginActivity.this, "网络忘记连接啦！",
			// Toast.LENGTH_SHORT).show();
			// 当前网络不可用
			User user = db.findFirst(Selector.from(User.class)
					.where("loginName", "=", UserName)
					.and("password", "=", Password));
			if (user != null) {
				Toast.makeText(LoginActivity.this, "离线登录中", Toast.LENGTH_SHORT)
						.show();
				Intent intent = new Intent(LoginActivity.this,
						MainActivity.class);
				startActivity(intent);
				finish();
			} else {
				return;
			}
		} else {
			if (!isLoginNameValid(UserName)) {
				Toast.makeText(LoginActivity.this, "账号只允许输入数字、字母、下划线",
						Toast.LENGTH_SHORT).show();
				return;
			} else if (!isPasswordValid(Password)) {
				Toast.makeText(LoginActivity.this, "密码由6-16位数字、字母组成",
						Toast.LENGTH_SHORT).show();
				return;
			}

			String url = C.HTTP_URL_LOGIN;
			// {loginName}/{password}/{imei}/{imsi}/{appVer}/{osType}/{osVer}/{manufacture}/{phoneModel}/{rom}/{ram}/{sd}/{freeRom}/{freeRam}/{freeSd}/{screenX}/{screenY}/{network}
			url = url
					.replace("{loginName}", UserName + "")
					.replace("{password}", Password)
					.replace("{imei}", logLogin.getImei() + "")
					.replace("{imsi}", logLogin.getImsi() + "")
					.replace("{appVer}", logLogin.getAppVer() + "")
					.replace("{osType}", logLogin.getOsType() + "")
					.replace("{osVer}", logLogin.getOsVer() + "")
					.replace("{manufacture}", logLogin.getManufacture() + "")
					.replace("{phoneModel}", logLogin.getPhoneModel() + "")
					.replace("{rom}", logLogin.getRom() + "")
					.replace("{ram}", logLogin.getRam() + "")
					.replace("{sd}", logLogin.getSd() + "")
					.replace("{freeRom}", logLogin.getFreeRom() + "")
					.replace("{freeRam}", logLogin.getFreeRam() + "")
					.replace("{freeSd}", logLogin.getFreeSd() + "")
					.replace("{screenX}", logLogin.getScreenX() + "")
					.replace("{screenY}", logLogin.getScreenY() + "")
					.replace(
							"{network}",
							logLogin.getNetwork() + "?device_tokens="
									+ BaseRegistrar.getRegistrationId(this));
			System.out.println(url);
			HttpUtils http = new HttpUtils();
			http.send(HttpRequest.HttpMethod.GET, url,
					new RequestCallBack<String>() {
						@Override
						public void onSuccess(ResponseInfo<String> responseInfo) {
							System.out.println("onSuccess"
									+ responseInfo.result);
							JsonResult result = OtherUtils
									.genJsonResult(responseInfo);
							if (result != null && result.getResult() == 0
									&& result.getObject() != null) {
								System.out.println("=======成功=========");
								// List<User> expList = JSON.parseArray(result
								// .getObject().toString(), User.class);
								User user = JSON.parseObject(result.getObject()
										.toString(), User.class);
								db.deleteAll(Selector.from(User.class));
								db.save(user);
								AppUseInfo aui = db.getFirst(AppUseInfo.class);
								aui.setUserId(user.getUserId());
								aui.setLogin(true);
								db.saveOrUpdate(aui);
								Toast.makeText(LoginActivity.this, "登录成功",
										Toast.LENGTH_SHORT).show();
								Intent intent = new Intent(LoginActivity.this,
										MainActivity.class);
								startActivity(intent);
								finish();
							} else {
								toastShow(getResources().getString(
										R.string.login_error));
							}
						}

						@Override
						public void onFailure(HttpException error, String msg) {
							System.out.println("onSuccess" + msg);
							toastShow("服务器被修空调的搬走啦！");
						}
					});
		}
	}

	// @OnClick(value = { R.id.login_login })
	// public void login_loginClick(View v) {
	// System.out.println("==========点击注册==========");
	// }
	//
	// @OnClick(value = { R.id.login_bt_forget })
	// public void login_bt_forgetClick(View v) {
	// System.out.println("==========点击忘记密码==========");
	// }

	public static boolean checkNetWorkStatus(Context context) {
		boolean result;
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netinfo = cm.getActiveNetworkInfo();
		if (netinfo != null && netinfo.isConnected()) {
			result = true;
			System.out.println("网络已经连接");
		} else {
			result = false;
			System.out.println("网络木有连接啊");
		}
		return result;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			AppUtil.AppOut(keyCode, event, this);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 验证密码输入格式 [0-9A-Za-z]*
	 * 
	 * @param string
	 * @return matcher.matches()
	 */
	public static boolean isPasswordValid(String string) {

		String expression = "[0-9A-Za-z]*";
		CharSequence inputStr = string;

		Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(inputStr);
		return matcher.matches();
	}

	/**
	 * 验证账号输入格式 [A-Za-z0-9_]+
	 * 
	 * @param string
	 * @return matcher.matches()
	 */
	public static boolean isLoginNameValid(String string) {

		String expression = "[A-Za-z0-9_]+";
		CharSequence inputStr = string;

		Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(inputStr);
		return matcher.matches();
	}
}
